// ignore_for_file: file_names, must_be_immutable, constant_identifier_names, slash_for_doc_comments, avoid_unnecessary_containers, prefer_const_constructors, unnecessary_cast, sized_box_for_whitespace, prefer_function_declarations_over_variables, overridden_fields, annotate_overrides, prefer_const_literals_to_create_immutables, unnecessary_null_comparison, deprecated_member_use

import 'dart:math';
import 'dart:async';
import 'package:mybase/base/tool/globalMethod/FFSafeValue.dart';
import 'package:synchronized/synchronized.dart';

/// 多任务队列
/// 用处不大
class FFMultiTaskManager {
  // 单例公开访问点
  factory FFMultiTaskManager() => _sharedInstance();

  // 静态、同步、私有访问点
  static FFMultiTaskManager _sharedInstance() {
    return _instance;
  }

  // 静态私有成员，没有初始化
  static final FFMultiTaskManager _instance = FFMultiTaskManager._();

  // 私有构造函数
  FFMultiTaskManager._() {}

  final Lock _lock = Lock(reentrant: true);
  int _currentUploadCount = 0;
  final List<FFMultiTask> _taskQueue = [];

  /// 最大的任务数量
  int maxUploadCount = 2;
  FFIMultiTaskDelegate? deleagte;

  /// 开始
  void start() {
    for (int i = 0; i < maxUploadCount; i++) {
      _startNextTask();
    }
  }

  /// 添加任务
  // 调用在start()之后，isStarted设置true
  Future<void> addTask(
    FFMultiTask task, {
    bool isStarted = true,
  }) async {
    await _lock.synchronized(() {
      _taskQueue.add(task);
    });

    if (isStarted == false) return;
    _startNextTask();
  }

  // 下一个任务
  Future<void> _startNextTask() async {
    FFMultiTask? task = await _lock.synchronized<FFMultiTask?>(() {
      if (_currentUploadCount >= maxUploadCount) {
        //print("当前任务数已满");
        return null;
      }

      var task = globalSafeValueFromList<FFMultiTask>(_taskQueue, 0);
      if (task == null) {
        //print("所有任务执行完成");
        deleagte?.allTaskComplete();
        return null;
      }

      _taskQueue.removeAt(0);
      _currentUploadCount++;
      return task;
    });

    _executeTask(task);
  }

  Future<void> _executeTask(FFMultiTask? task) async {
    if (task == null) {
      //print("_executeTask task null");
      return;
    }

    //print('开始任务: ${task.name}');
    await task.execute?.call(task, task.params);
    _lock.synchronized(() => _currentUploadCount = min(0, _currentUploadCount - 1));
    //print('完成任务: ${task.name}');
    _startNextTask();
  }
}

abstract class FFMultiTask {
  String? name;
  Map<String, dynamic>? params;
  Future Function(dynamic obj, Map<String, dynamic>? params)? execute;
}

abstract class FFIMultiTaskDelegate {
  // 所有任务完成
  void allTaskComplete();
}
